<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
    <style>
        .chart-container {
            width: 100%;
            height: 220px;
            margin-bottom: 15px;
        }

        .trend-container {
            width: 100%;
            height: 250px;
        }

        .stat-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            margin: 15px 0;
        }

        .stat-card {
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
        }

        .stat-card p:first-child {
            color: #666;
            font-size: 14px;
            margin-bottom: 5px;
        }

        .stat-card p:last-child {
            font-size: 18px;
            font-weight: bold;
            margin: 0;
        }

        .filter-bar {
            display: flex;
            margin: 10px 0;
            overflow-x: auto;
            padding-bottom: 5px;
        }

        .filter-bar button {
            margin-right: 10px;
            white-space: nowrap;
        }

        .radio-group {
            display: flex;
            align-items: center;
            margin: 10px 0;
            gap: 20px;
        }

        .radio-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        input[type="radio"] {
            width: 16px;
            height: 16px;
        }

        .circle-center-font {
            font-size: 14px;
            position: absolute;
            margin-left: 28%;
            margin-top: 16%;
        }
    </style>
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            故障看板
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;">
        <ul class="aui-list aui-form-list">
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div>统计时间</div>
                    <input type="text" class="aui-input" style="width: 80%;" id="nowDateTime" readonly>
                </div>
            </li>
        </ul>
        <div style="width:100%;margin-top:2%;"></div>

        <!-- 故障状态分布图表 -->
        <div style="background-color:white; padding:10px; margin-top:10px; border-radius:5px;">
            <div class="radio-group">
                <div class="radio-item">
                    <input type="radio" name="faultType" id="equipmentFault" value="equipment" checked
                        onclick="loadDashboardData()">
                    <label for="equipmentFault">仅设备故障</label>
                </div>
                <div class="radio-item">
                    <input type="radio" name="faultType" id="shutdownFault" value="shutdown"
                        onclick="loadDashboardData()">
                    <label for="shutdownFault">仅停机故障</label>
                </div>
            </div>

            <div class="circle-center-font">
                <span style="font-size: 16px;margin-left: 10px" id="centerUnfixed">14</span>
                <br>
                <span style="font-size: 14px">未修复</span>
                <br>
                <span style="font-size: 14px;color:red;margin-left: -20px" id="centerTodayNew">今日新增 0</span>
            </div>

            <div class="chart-container" id="faultStatusChart" style="position: relative;"></div>
        </div>

        <!-- 关键指标统计 -->
        <div style="background-color:white; padding:10px; margin-top:10px; border-radius:5px;">
            <div class="stat-grid">
                <div class="stat-card">
                    <p>停机故障</p>
                    <p id="totalFaults">14</p>
                </div>
                <div class="stat-card">
                    <p>响应超时</p>
                    <p id="unfixedFaults">14</p>
                </div>
                <div class="stat-card">
                    <p>维修超时</p>
                    <p id="todayNewFaults">5</p>
                </div>
                <div class="stat-card">
                    <p>暂停中</p>
                    <p id="fixedFaults">0</p>
                </div>
                <!-- <div class="stat-card">
                    <p>停机故障</p>
                    <p id="shutdownFaults">0</p>
                </div>
                <div class="stat-card">
                    <p>响应超时</p>
                    <p id="responseTimeout">4</p>
                </div>
                <div class="stat-card">
                    <p>维修超时</p>
                    <p id="repairTimeout">12</p>
                </div>
                <div class="stat-card">
                    <p>暂停中</p>
                    <p id="pausedFaults">0</p>
                </div> -->
            </div>
        </div>

        <!-- 部门故障统计表格 -->
        <div style="background-color:white; padding:10px; margin-top:10px; border-radius:5px; overflow-x:auto;">
            <h3 style="margin-top:0;">部门故障统计</h3>
            <table class="table" style='width:100%;' id="deptFaultTable">
                <thead>
                    <tr
                        style="text-align: center;background-color: #DCE9F2;color: #467aa7;font-size: 10px;font-weight: bold;">
                        <td>部门</td>
                        <td>未修复</td>
                        <td>今日新增</td>
                        <td>待应答</td>
                        <td>已应答</td>
                        <td>已处理</td>
                        <td>已关闭</td>
                    </tr>
                </thead>
                <tbody id="deptFaultTbody">
                    <!-- 数据将通过JS动态填充 -->
                </tbody>
            </table>
        </div>

        <!-- 故障趋势图 -->
        <div style="background-color:white; padding:10px; margin-top:10px; border-radius:5px;">
            <h3 style="margin-top:0;">故障次数趋势</h3>
            <div class="filter-bar">
                <button class="aui-btn aui-btn-info" onclick="changeTrendPeriod(7)">近7天</button>
                <button class="aui-btn" onclick="changeTrendPeriod(15)">近15天</button>
                <button class="aui-btn" onclick="changeTrendPeriod(30)">近30天</button>
                <button class="aui-btn" onclick="changeTrendPeriod(90)">近3个月</button>
            </div>
            <div class="trend-container" id="faultTrendChart"></div>
        </div>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/echarts.min.js"></script>
<script type="text/javascript">
    // 全局变量：图表实例、当前趋势周期、接口返回的完整趋势数据（缓存用）
    var faultStatusChart = null;
    var faultTrendChart = null;
    var currentTrendPeriod = 7; // 默认近7天
    var fullTrendData = []; // 缓存接口返回的近三个月完整趋势数据

    // 初始化页面
    apiready = function () {
        updateDateTime();
        initCharts();
        loadDashboardData();
    }

    // 更新日期时间显示
    function updateDateTime() {
        var now = new Date();
        var dateTimeString = "截止 " + now.toLocaleString();
        $("#nowDateTime").val(dateTimeString);
    }

    // 初始化图表
    function initCharts() {
        faultStatusChart = echarts.init(document.getElementById('faultStatusChart'));
        faultTrendChart = echarts.init(document.getElementById('faultTrendChart'));
        // 窗口 resize 重绘图表
        window.addEventListener('resize', function () {
            faultStatusChart.resize();
            faultTrendChart.resize();
        });
    }

    // 加载看板数据（核心：缓存完整趋势数据）
    function loadDashboardData() {
        api.showProgress({ title: '加载中...', text: '请稍候' });

        // 获取单选框值
        var selectedValue = $('input[name="faultType"]:checked').val();
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getEquipmentFaultKanbanData";

        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30000,
            returnAll: false,
            data: { values: { type: selectedValue, un: un } }
        }, function (ret, err) {
            api.hideProgress();
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                if (myobj.code == "0") {
                    // 1. 缓存接口返回的完整趋势数据（适配date和daily_count字段）
                    fullTrendData = myobj.trendData || [];
                    
                    // 2. 构建看板数据
                    var dashboardData = {
                        statistics: myobj.statistics || {
                            totalFaults: 14,
                            unfixedFaults: 14,
                            todayNewFaults: 5,
                            fixedFaults: 0,
                            shutdownFaults: 0,
                            responseTimeout: 4,
                            repairTimeout: 12,
                            pausedFaults: 0
                        },
                        statusDistributionName: ['待应答', '已应答', '已处理', '已关闭'],
                        statusDistribution: myobj.statusDistribution || [],
                        deptFaults: myobj.deptFaultList
                    };

                    // 3. 更新页面所有模块
                    updateStatisticData(dashboardData.statistics);
                    updateDeptFaultTable(dashboardData.deptFaults);
                    updateFaultStatusChart(dashboardData.statusDistribution, dashboardData.statusDistributionName);
                    updateFaultTrendChart(filterTrendDataByPeriod(currentTrendPeriod));

                    api.toast({ msg: "数据加载成功", duration: 2000 });
                    updateDateTime();
                } else {
                    $api.html($api.byId("deptFaultTbody"), '<tr style="text-align:center;"><td colspan="6">' + myobj.message + '</td></tr>');
                    api.toast({ msg: myobj.message, duration: 3000 });
                }
            } else {
                $api.html($api.byId("deptFaultTbody"), '<tr style="text-align:center;"><td colspan="6">获取数据失败，请重试</td></tr>');
                api.toast({ msg: "获取数据失败: " + (err.msg || '网络异常'), duration: 3000 });
            }
        });
    }

    // 核心：根据当前周期筛选趋势数据（从完整数据中取近N天）
    function filterTrendDataByPeriod(periodDays) {
        if (fullTrendData.length === 0) {
            // 缓存无数据时生成模拟数据
            return generateMockTrendData(periodDays);
        }

        // 1. 获取当前日期（yyyy-MM-dd 格式）
        var today = new Date().toISOString().split('T')[0];
        // 2. 计算周期起始日期（当前日期 - periodDays 天）
        var startDate = new Date();
        startDate.setDate(startDate.getDate() - periodDays + 1); // 包含今日
        startDate = startDate.toISOString().split('T')[0];

        // 3. 筛选起始日期到今日的数据（使用date和daily_count字段）
        var filteredData = fullTrendData.filter(item => {
            // 确保item是对象且包含date字段
            if (!item || typeof item !== 'object' || !item.date) return false;
            var itemDate = item.date;
            return itemDate >= startDate && itemDate <= today;
        });

        // 4. 生成周期内所有日期（补全无数据的日期）
        var dateList = [];
        var tempDate = new Date(startDate);
        while (tempDate <= new Date(today)) {
            dateList.push(tempDate.toISOString().split('T')[0]);
            tempDate.setDate(tempDate.getDate() + 1);
        }

        // 5. 日期对齐：有数据填daily_count，无数据填0
        var finalDates = [];
        var finalCounts = [];
        dateList.forEach(date => {
            // 查找对应日期的数据（匹配date字段）
            var matchItem = filteredData.find(item => item.date === date);
            finalDates.push(formatDateToShort(date)); // 转换为 "8-1" 格式
            finalCounts.push(matchItem ? (parseInt(matchItem.daily_count || 0, 10)) : 0);
        });

        return { dates: finalDates, counts: finalCounts };
    }

    // 日期格式转换（yyyy-MM-dd → M-d）
    function formatDateToShort(dateStr) {
        if (!dateStr) return '';
        var [year, month, day] = dateStr.split('-');
        return `${parseInt(month, 10)}-${parseInt(day, 10)}`;
    }

    // 生成模拟趋势数据（缓存无数据时使用）
    function generateMockTrendData(periodDays) {
        var dates = [];
        var counts = [];
        var today = new Date();
        for (let i = periodDays - 1; i >= 0; i--) {
            var tempDate = new Date(today);
            tempDate.setDate(today.getDate() - i);
            dates.push(formatDateToShort(tempDate.toISOString().split('T')[0]));
            counts.push(Math.floor(Math.random() * 8) + 1);
        }
        return { dates: dates, counts: counts };
    }

    // 更新统计数据（含饼图中心文字）
    function updateStatisticData(statistics) {
        document.getElementById('totalFaults').textContent = statistics.totalFaults;
        document.getElementById('unfixedFaults').textContent = statistics.unfixedFaults;
        document.getElementById('todayNewFaults').textContent = statistics.todayNewFaults;
        document.getElementById('fixedFaults').textContent = statistics.fixedFaults;
        // document.getElementById('shutdownFaults').textContent = statistics.shutdownFaults;
        // document.getElementById('responseTimeout').textContent = statistics.responseTimeout;
        // document.getElementById('repairTimeout').textContent = statistics.repairTimeout;
        // document.getElementById('pausedFaults').textContent = statistics.pausedFaults;
        
        // 同步更新饼图中心数据
        document.getElementById('centerUnfixed').textContent = statistics.unfixedFaults;
        
    }

    // 更新部门故障表格
    function updateDeptFaultTable(deptFaults) {
        var tbody = document.getElementById('deptFaultTbody');
        tbody.innerHTML = '';
        if (deptFaults.length === 0) {
            tbody.innerHTML = '<tr style="text-align:center;font-size: 10px"><td colspan="6">暂无数据</td></tr>';
            return;
        }
        deptFaults.forEach((dept, index) => {
            var tr = document.createElement('tr');
            tr.style.textAlign = 'center';
            tr.style.fontSize = '10px';
            tr.style.backgroundColor = index % 2 === 0 ? '#F5F5F5' : 'white';
            tr.innerHTML = `
                <td>${dept.department || ''}</td>
                <td>${dept.unresolved_count || 0}</td>
                <td>${dept.new_today_count || 0}</td>
                <td>${dept.pending_response || 0}</td>
                <td>${dept.answered || 0}</td>
                <td>${dept.processed || 0}</td>
                <td>${dept.closed || 0}</td>
            `;
            tbody.appendChild(tr);
        });
    }

    // 更新故障状态图表
    function updateFaultStatusChart(statusData, statusDistributionName) {
        var option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)',
            },
            legend: {
                orient: 'vertical',
                right: 'right',
                icon: 'circle',
                itemGap: 20,
                padding: [50, 50, 0, 0],
                textStyle: { color: 'black' },
                data: statusDistributionName,
            },
            series: [
                {
                    name: '',
                    type: 'pie',
                    radius: ['40%', '60%'],
                    center: ['35%', '45%'],
                    data: statusData,
                    label: {
                        formatter: function (params) {
                            if (params.value == '0') return '';
                            return `${params.name}\n(${params.value}_${Math.round(params.percent)}%)`
                        },
                    },
                    labelLine: {
                        show: true,
                        length: 10,
                        length2: 10,
                    },
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)',
                        },
                    },
                },
            ],
        };
        faultStatusChart.setOption(option);
    }

    // 更新故障趋势图表
    function updateFaultTrendChart(trendData) {
        var option = {
            tooltip: {
                trigger: 'axis'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: trendData.dates,
                axisLine: { show: true },
                axisTick: { show: false },
                axisLabel: { show: true },
                splitLine: { show: false }
            },
            yAxis: {
                type: 'value',
                axisLine: { show: true },
                axisTick: { show: false },
                axisLabel: { show: true },
                splitLine: { show: true }
            },
            series: [
                {
                    name: '故障数量',
                    type: 'line',
                    stack: 'Total',
                    data: trendData.counts,
                    lineStyle: { color: 'green', width: 3 },
                    symbol: 'circle',
                    symbolSize: 8
                }
            ]
        };
        faultTrendChart.setOption(option);
    }

    // 切换趋势图时间周期
    function changeTrendPeriod(days) {
        // 更新按钮样式
        var buttons = document.querySelectorAll('.filter-bar button');
        buttons.forEach(btn => btn.className = btn.className.replace('aui-btn-info', ''));
        event.currentTarget.className += ' aui-btn-info';
        
        // 更新周期并刷新趋势图（使用缓存的完整数据筛选）
        currentTrendPeriod = days;
        updateFaultTrendChart(filterTrendDataByPeriod(currentTrendPeriod));
    }

    // 返回按钮
    function closeWin() {
        api.closeWin({});
    }
</script>

</html>
    